<template>
  <div class="app-container">

    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">

      <el-form-item label="日志类型" prop="productId">
        <el-select
          multiple
          filterable
          allow-create
          clearable
          v-model="logType"
          placeholder="请选择日志类型"
        >
          <el-option
            v-for="dict in dict.type.iot_log_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>


      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table ref="deviceTable" v-loading="loading" :data="logList">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="类型" align="center" prop="type.text" />
      <el-table-column label="日期" :formatter="timestampFormatter" sortable align="center" prop="timestamp"/>
      <el-table-column label="内容" show-overflow-tooltip align="center" prop="content"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCheck(scope.row)"
            v-hasPermi="['iot:device:query']"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 详情查看 -->
    <el-dialog
      :title=preview.title
      :visible.sync="preview.open"
      width="30%"
    >
      <pre><code v-if="preview.open" class="hljs" v-html="highlightedCode()"></code></pre>
      <span slot="footer" class="dialog-footer">
        <el-button @click="preview.open = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { mapState } from 'vuex'
import { listLog } from '@/api/iot/device'
import { parseTime } from "@/utils/ruoyi";
import hljs from "highlight.js/lib/highlight";
import "highlight.js/styles/github-gist.css";
hljs.registerLanguage("json", require("highlight.js/lib/languages/json"));

export default {
  name: 'LogManagement',
  // 字典
  dicts: ['iot_log_type'],
  data() {
    return {
      // 设备表格数据
      logList: [],
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 日志类型
      logType: [],
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        terms: [],
        sorts: []
      },
      // 预览参数
      preview: {
        open: false,
        title: '详细信息',
        data: ''
      }
    }
  },
  computed: {
    ...mapState({
      deviceId: state => state.device.deviceId,
      tabsActiveName: state => state.device.tabsActiveName,
      detailedPageVisible: state => state.device.detailedPageVisible,
    })
  },
  watch: {
    tabsActiveName(tagName) {
      if (tagName === 'log' && this.logList.length === 0) {
        this.getList();
      }
    },

    /** 监听详情页面显示状态*/
    detailedPageVisible(state) {
      // 详情页面关闭时清空日志页面数据
      if (!state) {
        this.logList = [];
      }
    }
  },
  methods: {
    getList() {
      this.loading = true;
      this.setQueryParams();
      const deviceId = this.deviceId;
      listLog(deviceId, this.queryParams).then(({ data }) => {
        this.logList = data && data.data;
        this.total = data.total;
        this.loading = false;
      });
    },
    resetQuery() {
      this.dateRange = [];
      this.logType = [];
      this.queryParams.terms = [];
      this.queryParams.sorts = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 设置查询参数 */
    setQueryParams() {

      this.queryParams.terms = [];
      this.queryParams.sorts = [];
      this.queryParams.pageIndex = this.queryParams.pageNum - 1;

      this.queryParams.sorts.push({
        name: 'timestamp',
        order: 'desc'
      });

      this.queryParams.terms.push({
        column: 'deviceId',
        value: this.deviceId
      });

      if (this.logType.length > 0) {
        this.queryParams.terms.push({
          column: 'type$IN',
          value: this.logType.join()
        });
      }

      if (this.dateRange && this.dateRange.length > 0) {
        this.queryParams.terms.push({
          column: 'timestamp$BTW',
          value: this.dateRange.join()
        });
      }
    },
    /** 查看按钮操作 */
    handleCheck(row) {
      this.preview.data = JSON.parse(row.content);
      this.preview.open = true;
    },

    /**
     * 时间戳格式化
     * @param row
     * @param column
     * @param cellValue
     * @returns {*}
     */
    timestampFormatter(row, column, cellValue) {
      return parseTime(cellValue);
    },

    /** json code 高亮显示*/
    highlightedCode() {
      const data = JSON.stringify(this.preview.data, null, 2) || '';
      const result = hljs.highlight('json',  data, true);
      return result.value || '&nbsp;';
    }
  }
}
</script>

<style scoped>
</style>
